package network

import (
	"gitee.com/amoyx/cloud-provider/pkg/cloud/huawei/models"
	regionv2 "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/ecs/v2/region"
	vpcv2 "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/vpc/v2"
	"github.com/huaweicloud/huaweicloud-sdk-go-v3/services/vpc/v2/model"
	"strings"
)

type SubnetGreeter interface {
	Subnets(region string) SubnetInterface
}

type SubnetInterface interface {
	DescribeSubnet(id string) (result models.SubnetResponse, err error)
	ListAllSubnets() (list []models.SubnetResponse, err error)
	ListSubnetsByVpcId(vpcId string) (list []models.SubnetResponse, err error)
}

type subnet struct {
	network *Network
	region  string
	client  *vpcv2.VpcClient
}

func newSubnet(network *Network, region string) SubnetInterface {
	v := &subnet{
		network: network,
		region:  region,
	}
	_client := vpcv2.NewVpcClient(
		vpcv2.VpcClientBuilder().
			WithRegion(regionv2.ValueOf(region)).
			WithCredential(network.credentials).
			Build())
	v.client = _client
	return v
}

func (s *subnet) DescribeSubnet(id string) (result models.SubnetResponse, err error) {
	list, err := s.query(id, "")
	if len(list) > 0 {
		result = list[0]
	}
	return
}

func (s *subnet) ListSubnetsByVpcId(vpcId string) (list []models.SubnetResponse, err error) {
	return s.query("", vpcId)
}

func (s *subnet) ListAllSubnets() (list []models.SubnetResponse, err error) {
	return s.query("", "")
}

func (s *subnet) query(id string, vpcId string) (list []models.SubnetResponse, err error) {
	var subnets []model.Subnet
	var response2 *model.ListSubnetsResponse
	var response *model.ShowSubnetResponse
	if strings.TrimSpace(id) != "" {
		request := &model.ShowSubnetRequest{}
		request.SubnetId = id
		response, err = s.client.ShowSubnet(request)
	} else {
		request2 := &model.ListSubnetsRequest{}
		if strings.TrimSpace(vpcId) != "" {
			request2.VpcId = &vpcId
		}
		response2, err = s.client.ListSubnets(request2)
	}
	if err != nil {
		return
	}
	subnets = append(subnets, *response.Subnet)
	subnets = append(subnets, *response2.Subnets...)
	for _, row := range subnets {
		var dnslist []string
		for _, dns := range row.DnsList {
			dnslist = append(dnslist, dns)
		}
		list = append(list, models.SubnetResponse{
			Id:               row.Id,
			Name:             row.Name,
			Cidr:             row.Cidr,
			GatewayIp:        row.GatewayIp,
			Description:      row.Description,
			AvailabilityZone: row.AvailabilityZone,
			Status:           row.Status.Value(),
			DnsList:          dnslist,
			CreatedAt:        row.CreatedAt,
			UpdatedAt:        row.UpdatedAt,
			VpcId:            row.VpcId,
		})
	}
	return
}
